<template>
	<div class="container">
		<div class="message-container">
			<div v-for="(msg, index) in this.item.msgs" :key="index" class="clearfix"
				 :style="{ 'margin-top': index === 0 ? '0px' : '10px' }">
				<img :src="$store.state.info.imgurl" alt="" v-if="msg.isMe"
					 :style="{ float: msg.isMe ? 'right' : null, 'margin-right': '10px' }"/>
				<img :src="item.imgurl" alt="" v-if="!msg.isMe"/>
				<div class="msg-content" :style="{
            float: msg.isMe ? 'right' : null,
            'margin-right': msg.isMe ? '10px' : '0px',
            'margin-left': msg.isMe ? '0px' : '10px',
          }">
					<!-- {{ msg.content }} -->
					<div v-html="msg.content != '' ? msg.content : null"></div>
				</div>
			</div>
		</div>

		<div id="drag" v-show="showed" @mousedown="resize" style="
        width: calc(100% - 300px);
        cursor: n-resize;
        border-top: 2px solid #fff;
        position: absolute;
        bottom: 200px;
        background-color: #ffffff;
      "></div>

		<div id="send" v-show="showed">
			<div class="tool-bar">
				<!-- <i class="el-icon-eleme" @click.stop="showEmoji  = !showBrow"></i> -->
				<i class="el-icon-folder-opened" @click="handleFile"> </i>
				<input type="file" ref="upFile" name="file" multiple="multiple" style="display: none"/>

				<i class="el-icon-scissors"></i>
				<i class="el-icon-chat-dot-round"></i>
				<i class="el-icon-phone-outline" @click="handleWebRTC"></i>
			</div>
			<div id="input" contenteditable="true" ref="input"></div>
			<button @click="send">fason</button>
		</div>
	</div>
</template>

<script>
	import request from "../../api/request";

	const FormData = require("form-data");
	const {ipcRenderer} = window.require("electron");

	export default {
		name: "chat",
		props: {},
		components: {},
		data() {
			return {
				item: {},
				showed: false,
				socket: this.$store.state.socket,
				fileList: [],
			};
		},
		computed: {},
		watch: {
			$route() {
				this.item = this.$route.params;
			},
			item(nVal, oVal) {
				this.showed = Object.keys(this.item).length > 0;
			},
		},
		created() {
		},
		mounted() {
			document.onmouseup = function () {
				document.onmousedown = null;
				document.onmousemove = null;
			};
		},
		methods: {
			resize(e) {
				let initY = e.clientY;
				let sendNode = document.getElementById("send");
				let dragNode = document.getElementById("drag");
				let messageContainer =
						document.getElementsByClassName("message-container")[0];
				let oy = sendNode.offsetHeight;
				let doy = parseInt(document.getElementById("drag").style.bottom);

				document.onmousemove = function (even) {
					// console.log("cur_y", even.clientY);
					let dy = initY - even.clientY;
					sendNode.style.height = dy + oy + "px";
					dragNode.style.bottom = doy + dy + 15 + "px";
					messageContainer.style["margin-bottom"] = doy + dy + 15 + "px";
				};
			},
			base64ToBlob(img) {
				const arr = img.split(",");
				const mime = arr[0].match(/:(.*?);/)[1];
				const bstr = atob(arr[1]);
				let n = bstr.length;
				const u8arr = new Uint8Array(n);

				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new Blob([u8arr], {type: mime});
			},
			async send() {
				let imgs = this.$refs.input.querySelectorAll("img");
				let content = this.$refs.input.innerHTML.toString();
				if (content == "") {
					window.globalEvents.$emit("handleBottom");
					return;
				}
				if (imgs != null) {
					for (let i = 0; i < imgs.length; i++) {
						if (imgs[i].src.startsWith("data:image")) {
							const imgStream = this.base64ToBlob(imgs[i].src);
							const data = new FormData();
							data.append("file", imgStream, "img.png");
							const res = await request({
								method: "post",
								url: "api/file_upload",
								data: data,
								headers: {"Content-Type": "multipart/form-data"},
							});
							if (res.status == 200 && res.data != null) {
								const path = res.data.path.replaceAll("\\", "/");
								imgs[i].src = "http://127.0.0.1:8081/" + path;
							} else {
								alert("请求图片有误");
							}
						}
					}
					content = this.$refs.input.innerHTML.toString();
					this.$refs.input.innerHTML = null;
				}

				const msg = {
					userId: this.$store.state.info.id,
					peerId: this.item.groupId, // 群id或好友id
					content: content,
					type: this.item.type, //标识发送给个人还是发送给群
				};
				//把消息显示到发送区上方
				window.globalEvents.$emit("handleMessage", null, msg);
				//发送消息到服务器
				this.$sendToWs(msg)
				window.globalEvents.$emit("handleBottom");
			},
			handleFile() {
				let fileRefs = this.$refs.upFile;
				self = this;
				this.$refs.upFile.onchange = function (e) {
					for (let i = 0; i < fileRefs.files.length; i++) {
						self.uploadFile(fileRefs.files[i], fileRefs.files[i].name);
					}
				};
				this.$refs.upFile.click();
			},
			uploadFile(file, name) {
				let stream = new Blob([file]);
				const data = new FormData();
				data.append("file", stream, name);
				request({
					method: "post",
					url: "api/file_upload",
					data: data,
					headers: {"Content-Type": "multipart/form-data"},
				}).then(function (res) {
					if (res.status == 200 && res.data != null) {
						const path = res.data.path.replaceAll("\\", "/");
						let fileUrl = "http://127.0.0.1:8081/" + path;
					} else {
						alert("上传失败");
					}
				});
			},
			handleWebRTC() {
				//在开启视频通话前，询问服务器对方是否在线
				this.$sendToWs({type: "isOnline", userId: this.$store.state.info.id, peerId: this.item.groupId})
			},
		},
	};
</script>
<style scoped>
	.message-container {
		height: 100%;
		margin-bottom: 200px;
		padding-bottom: 10px;
	}

	.message-container div.clearfix > img {
		width: 33px;
		height: 33px;
		border-radius: 5px;
		vertical-align: top;
	}

	.msg-content {
		display: inline-block;
		background-color: #97df64;
		max-width: calc(100% - 110px);
		border-radius: 5px;
		padding: 10px 8px;
		word-wrap: break-word;
	}

	.clearfix {
		/* margin-top: 10px; */
		padding: 0 10px;
	}

	.clearfix:after {
		content: "";
		display: block;
		height: 0;
		clear: both;
		visibility: hidden;
	}

	.clearfix {
		/* 针对IE6、7专有 */
		*zoom: 1;
	}

	#send {
		position: fixed;
		bottom: 0px;
		left: 300px;
		right: 0px;
		height: 185px;
		background: #ffffff;
		padding: 0 20px 15px 20px;
	}

	#input {
		height: calc(100% - 12px);
		outline: none;
		overflow-y: auto;
	}

	#input::-webkit-scrollbar {
		width: 0;
		height: 0;
	}
</style>
